package tech.ezrealc.fall2023.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import tech.ezrealc.fall2023.exception.RelatedRecordException;
import tech.ezrealc.fall2023.exception.TokenInvalidException;
import tech.ezrealc.fall2023.model.common.ResponseModel;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(TokenInvalidException.class)
    @ResponseStatus(HttpStatus.FORBIDDEN)
    ResponseModel handleTokenInvalidException(Exception exception) {
        log.error(exception.getMessage(), exception);
        return ResponseModel.failure("Token无效");
    }

    @ExceptionHandler(RelatedRecordException.class)
    @ResponseStatus(HttpStatus.CONFLICT)
    ResponseModel handleRelatedRecordException(Exception exception){
        log.error(exception.getMessage(), exception);
        return ResponseModel.failure("存在关联记录，请检查");
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    ResponseModel handleException(Exception exception) {
        log.error(exception.getMessage(), exception);
        return ResponseModel.failure("未知错误");
    }
}
